package com.duowei.diandan.fragment;

import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.duowei.diandan.R;
import com.duowei.diandan.adapter.TicketSelectedAdapter;
import com.duowei.diandan.app.OrderList;
import com.duowei.diandan.bean.Money;
import com.duowei.diandan.bean.Payment;
import com.duowei.diandan.bean.Ticket;
import com.duowei.diandan.bean.UserCardInfo;
import com.duowei.diandan.constant.NetConfig;
import com.duowei.diandan.constant.PayType;
import com.duowei.diandan.constant.Settings;
import com.duowei.diandan.constant.SqlStr;
import com.duowei.diandan.databinding.CloudDetailFragmentBinding;
import com.duowei.diandan.db.AppDatabase;
import com.duowei.diandan.db.entry.Jgsz;
import com.duowei.diandan.db.entry.Wmlsb;
import com.duowei.diandan.db.entry.Wxfwqdz;
import com.duowei.diandan.event.ToastEvent;
import com.duowei.diandan.fragment.dialog.InputDialogFragment;
import com.duowei.diandan.fragment.dialog.TicketDialogFragment;
import com.duowei.diandan.impl.OnTicketClickListener;
import com.duowei.diandan.util.NetUtils;
import com.duowei.diandan.util.Post6Listener;
import com.duowei.diandan.util.ToastUtils;

import org.greenrobot.eventbus.EventBus;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

public class CloudDetailFragment extends BaseFragment implements OnTicketClickListener {
    public static final String TAG = "CloudDetailFragment";

    public static final String EXTRA_USER_CARD_INFO = "userCardInfo";

    private CloudDetailFragmentBinding mBinding;

    private UserCardInfo mUserCardInfo;
    private Ticket mStoredValueTicket;
    private Ticket mIntegralTicket;

    private Money mMoney;

    private TicketSelectedAdapter mTicketSelectedAdapter;

    private int mCloudTicketNum;

    private List<Ticket> mTicketList;

    private Jgsz mJgsz;

    public static CloudDetailFragment newInstance(UserCardInfo userCardInfo) {

        Bundle args = new Bundle();
        args.putSerializable(EXTRA_USER_CARD_INFO, userCardInfo);

        CloudDetailFragment fragment = new CloudDetailFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mCloudTicketNum = Settings.CLOUD_TICKET_NUM;
        mMoney = OrderList.getInstance().getMoney();
        OrderList.getInstance().setPaymentList(null); // 清空
        mJgsz = getDb().jgszDao().findOne();

        Bundle args = getArguments();
        if (args != null) {
            mUserCardInfo = (UserCardInfo) args.getSerializable(EXTRA_USER_CARD_INFO);
            if (mUserCardInfo != null) {
                mStoredValueTicket = new Ticket("储值消费", mUserCardInfo.getCredit2(), PayType.STORED_VALUE_TYPE);
                mIntegralTicket = new Ticket("积分消费", mUserCardInfo.getCredit1(), PayType.INTEGRAL_TYPE);
            }
        }
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_cloud_detail, container, false);
        return mBinding.getRoot();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        mMoney.setPaidFloat(0); // 清空已付

        // 返回购物车按钮
        if (Settings.CLOUD_DETAIL_SHOW_BACK_CART) {
            mBinding.backCartButton.setVisibility(View.VISIBLE);

            mBinding.backCartButton.setOnClickListener(v -> {
                if (mOnButtonClickListener != null) {
                    mOnButtonClickListener.onBackCartClick();
                }
            });
        } else {
            mBinding.backCartButton.setVisibility(View.GONE);
        }

        mBinding.logoutButton.setOnClickListener(v -> {
            if (mOnButtonClickListener != null) {
                //设置选择的付款方式
                OrderList.getInstance().setPaymentList(null);

                mOnButtonClickListener.onLogoutClick();
            }
        });
        mBinding.confirmPayButton.setOnClickListener(v -> {
            if (mMoney.getUnpaidFloat() != 0) {
                EventBus.getDefault().post(new ToastEvent("未付清", false));
            } else {
                //设置选择的付款方式
                OrderList.getInstance().setPaymentList(mTicketSelectedAdapter.getSelectedList());

                if (mOnButtonClickListener != null) {
                    mOnButtonClickListener.onConfirmPayClick();
                }
            }
        });

        mBinding.weixinPayLayout.setOnClickListener(v -> {
            if (mMoney.getUnpaidFloat() <= 0) {
                EventBus.getDefault().post(new ToastEvent("已付清", false));
            } else {
                if (mOnButtonClickListener != null) {
                    //设置选择的付款方式
                    OrderList.getInstance().setPaymentList(mTicketSelectedAdapter.getSelectedList());

                    mOnButtonClickListener.onWeixinPayClick(mMoney.getUnpaidFloat());
                }
            }
        });

        mBinding.alipayLayout.setOnClickListener(v -> {
            if (mMoney.getUnpaidFloat() <= 0) {
                EventBus.getDefault().post(new ToastEvent("已付清", false));
            } else {
                if (mOnButtonClickListener != null) {
                    //设置选择的付款方式
                    OrderList.getInstance().setPaymentList(mTicketSelectedAdapter.getSelectedList());

                    mOnButtonClickListener.onAlipayClick(mMoney.getUnpaidFloat());
                }
            }
        });

        // --
        mBinding.setUser(mUserCardInfo);
        mBinding.setMoney(mMoney);
        setViewData();
        handleTable();
        OrderList.getInstance().computeCloudDiscount(mUserCardInfo);
    }

    private void setViewData() {
        mBinding.useCreditsView.setText(String.format(Locale.CHINA, "%.2f", mUserCardInfo.getCredit1()));
        mBinding.useMoneyView.setText(String.format(Locale.CHINA, "¥%.2f", mUserCardInfo.getCredit2()));

        Wxfwqdz wxfwqdz = AppDatabase.getDatabase().wxfwqdzDao().findOne();
        if (wxfwqdz != null && mUserCardInfo != null) {
            NetUtils.post6(NetConfig.getWeiXinServerUrl(wxfwqdz.getAndroidSip()),
                    SqlStr.getMemberTicket("" + wxfwqdz.getWeid(), mUserCardInfo.getFromUser()),
                    Ticket.class, new Post6Listener<Ticket>() {
                        @Override
                        public void onFail(Exception e) {
                            Log.e(TAG, "onFail: ", e);
                        }

                        @Override
                        public void onSuccess(List<Ticket> list) {
                            mTicketList = list;
                            int total = 0;
                            for (Ticket t : mTicketList) {
                                try {
                                    total += Integer.valueOf(t.num);
                                } catch (NumberFormatException e) {
                                    Log.e(TAG, "onSuccess: ", e);
                                }
                            }
                            mBinding.useTicketView.setText(String.format(Locale.CHINA, "%d张", total));
                        }
                    });
        }

        mBinding.payCouponLayout.setOnClickListener(v -> {
            if (mTicketList != null && mTicketList.size() > 0 && getFragmentManager() != null) {
                TicketDialogFragment ticketDialogFragment = TicketDialogFragment
                        .newInstance((ArrayList<Ticket>) mTicketList, mMoney);
                ticketDialogFragment.show(getFragmentManager(), null);
                ticketDialogFragment.setOnTicketClickListener(this);
            }
        });

        mBinding.payCreditsLayout.setOnClickListener(v -> {
            if (mIntegralTicket != null) {
                onTicketClick(mIntegralTicket);
            }
        });

        mBinding.payMoneyLayout.setOnClickListener(v -> {
            if (mStoredValueTicket != null) {
                onTicketClick(mStoredValueTicket);
            }
        });
    }

    @Override
    public void onTicketClick(Ticket ticket) {
        if (getFragmentManager() == null) {
            return;
        }

        PayType type = ticket.payType;
        InputDialogFragment fragment;
        if (type == PayType.STORED_VALUE_TYPE) {
            // 储值消费
            if (isTicketSelected(ticket)) {
                EventBus.getDefault().post(new ToastEvent("已选择过 储值消费", false));
                return;
            }

            if (mMoney.getUnpaidFloat() == 0) {
                EventBus.getDefault().post(new ToastEvent("已付清", false));
                return;
            }

            if (mJgsz != null && "1".equals(mJgsz.getBy22()) && mMoney.getDiscountFloat() > 0) {
                ToastUtils.show("使用余额付款,不享受优惠");

                OrderList.getInstance().recoverOriginPrice(() -> {
                    showStoredValueDialogFragment(ticket);
                });

            } else {
                showStoredValueDialogFragment(ticket);
            }

        } else if (type == PayType.INTEGRAL_TYPE) {
            // 积分消费
            if (isTicketSelected(ticket)) {
                EventBus.getDefault().post(new ToastEvent("已选择过 积分消费", false));
                return;
            }

            if (mMoney.getUnpaidFloat() == 0) {
                EventBus.getDefault().post(new ToastEvent("已付清", false));
                return;
            }

            float by3Money = 0.0f; // 积分可以抵扣的金额
            float by3 = 0.0f; // 积分统计
            List<Wmlsb> wmlsbList = AppDatabase.getDatabase().wmlsbDao().findAll();
            for (int i = 0; i < wmlsbList.size(); i++) {
                Wmlsb item = wmlsbList.get(i);
                // 判断是否有积分
                if (item.getBy3NonNull() > 0) {
                    by3Money += item.getSl() * item.getDj();
                    by3 += item.getSl() * item.getBy3();
                }
            }

            if (by3 > 0) {
                if (ticket.money < by3) {
                    EventBus.getDefault().post(new ToastEvent("积分不足", false));
                    return;
                }

                float minMoney = Math.min(mMoney.getUnpaidFloat(), by3Money);
                mTicketSelectedAdapter.add(new Payment("云会员-积分抵扣金额",
                        PayType.INTEGRAL_TYPE, minMoney, minMoney * by3 / by3Money));

                OrderList.getInstance().computeCloudMoneyWithPayment(mTicketSelectedAdapter.getSelectedList());

            } else {
                EventBus.getDefault().post(new ToastEvent("您未点能够参与积分兑换的产品", false));
            }

        } else if (type == PayType.COUPON_TYPE) {
            // 券
            if (isTicketSelected(ticket)) {
                EventBus.getDefault().post(new ToastEvent("已选择过 " + ticket.title, false));
                return;
            }

            if (mMoney.getUnpaidFloat() == 0) {
                EventBus.getDefault().post(new ToastEvent("已付清", false));
                return;
            }

            // 最低可使用券
            if (ticket.leastCost != null && mMoney.getTotalFloat() < ticket.leastCost) {
                EventBus.getDefault().post(new ToastEvent(String.format(Locale.CHINA,
                        "消费满%.2f可使用", ticket.leastCost), false));
                return;
            }

            // 设置中抵用券张数处理
            if (mCloudTicketNum > 0 && mCloudTicketNum <= getCouponTypeNum()) {
                EventBus.getDefault().post(new ToastEvent("只能使用" +
                        mCloudTicketNum + "张抵用券", false));
                return;
            }

            if (mJgsz != null && "1".equals(mJgsz.getBy57()) && mMoney.getDiscountFloat() > 0) {
                ToastUtils.show("使用优惠券付款,不享受优惠");

                OrderList.getInstance().recoverOriginPrice(() -> {
                    if (Settings.CLOUD_TICKET_DEFAULT_ONE) {
                        addTicketToTable(ticket, 1);

                    } else {
                        showCouponDialogFragment(ticket);
                    }
                });

            } else {
                if (Settings.CLOUD_TICKET_DEFAULT_ONE) {
                    addTicketToTable(ticket, 1);

                } else {
                    showCouponDialogFragment(ticket);
                }

            }
        }
    }

    /**
     * 显示余额输入窗口
     * <p>
     * param ticket
     */
    private void showStoredValueDialogFragment(Ticket ticket) {
        InputDialogFragment fragment = InputDialogFragment.newInstance("请输入付款金额",
                String.valueOf(Math.min(mMoney.getUnpaidFloat(), ticket.money)), true);
        fragment.show(getFragmentManager(), null);
        fragment.setOkBtnClickListener(text -> {
            float inputMoney = Float.valueOf(text);
            if (inputMoney > ticket.money) {
                EventBus.getDefault().post(new ToastEvent("输入金额大于实际拥有的金额", false));
                return;
            }

            // 0
            if (inputMoney == 0) {
                return;
            }

            mTicketSelectedAdapter.add(new Payment("云会员-储值消费",
                    PayType.STORED_VALUE_TYPE, Math.min(mMoney.getUnpaidFloat(), inputMoney)));

            OrderList.getInstance().computeCloudMoneyWithPayment(mTicketSelectedAdapter.getSelectedList());
        });
    }

    /**
     * 显示券输入窗口
     *
     * @param ticket
     */
    private void showCouponDialogFragment(Ticket ticket) {
        InputDialogFragment fragment = InputDialogFragment.newInstance("请输入抵用券使用张数", "1", false);
        fragment.show(getFragmentManager(), null);
        fragment.setOkBtnClickListener(text -> {
            try {
                int ticketNum = Integer.parseInt(text);
                addTicketToTable(ticket, ticketNum);

            } catch (NumberFormatException e) {
                showToast("输入错误,请正确输入抵用券张数", false);
            }
        });
    }

    /**
     * @param ticket    券
     * @param ticketNum 满减券输入数量;类别折扣券,单品折扣券,单品券默认数量为1张
     */
    private void addTicketToTable(Ticket ticket, int ticketNum) {
        if (ticketNum > Integer.valueOf(ticket.num)) {
            EventBus.getDefault().post(new ToastEvent("输入数量大于实际拥有数量", false));
            return;
        }

        // 设置中抵用券张数处理
        if (mCloudTicketNum > 0 && mCloudTicketNum < getCouponTypeNum() + ticketNum) {
            EventBus.getDefault().post(new ToastEvent("只能使用" +
                    mCloudTicketNum + "张抵用券", false));
            return;
        }

        // 0
        if (ticketNum == 0) {
            return;
        }

        if (ticketNum > 1 && (ticket.ticketType == 2 || ticket.ticketType == 3 || ticket.ticketType == 4)) {
            showToast(ticket.title + "只能使用1张", false);
            return;
        }

        if (ticket.ticketType == 1) {
            // 满减券
            // 张数取最小值
            int bestTickNum;
            float isFloat = mMoney.getUnpaidFloat() / ticket.money;
            try {
                bestTickNum = Integer.valueOf(String.valueOf(isFloat));
            } catch (NumberFormatException e) {
                bestTickNum = Math.round(isFloat + 0.5f);
            }

            float money = ticket.money * ticketNum; // 总的券价格
            int num = Math.min(ticketNum, bestTickNum);
            mTicketSelectedAdapter.add(new Payment("云会员-" + ticket.title, PayType.COUPON_TYPE,
                    BigDecimal.valueOf(ticket.money).multiply(BigDecimal.valueOf(num)).setScale(2, BigDecimal.ROUND_HALF_UP).floatValue(),
                    Math.min(mMoney.getUnpaidFloat(), money), num, ticket.id));

            OrderList.getInstance().computeCloudMoneyWithPayment(mTicketSelectedAdapter.getSelectedList());

        } else if (ticket.ticketType == 2) {
            // 类别折扣券,默认一张
            OrderList.getInstance().computeCateDiscount(ticket, discount -> {
                if (discount > 0) {
                    mTicketSelectedAdapter.add(new Payment("云会员-" + ticket.title, PayType.COUPON_TYPE, -1,
                            Math.min(mMoney.getUnpaidFloat(), discount), 1, ticket.id));

                    OrderList.getInstance().computeCloudMoneyWithPayment(mTicketSelectedAdapter.getSelectedList());
                } else {
                    showToast("当前选择的券不能使用,未发现优惠项", false);
                }
            });
        } else if (ticket.ticketType == 3) {
            // 单品折扣券,默认一张
            OrderList.getInstance().computeSingleDiscount(ticket, discount -> {
                if (discount > 0) {
                    mTicketSelectedAdapter.add(new Payment("云会员-" + ticket.title, PayType.COUPON_TYPE, -1,
                            Math.min(mMoney.getUnpaidFloat(), discount), 1, ticket.id));

                    OrderList.getInstance().computeCloudMoneyWithPayment(mTicketSelectedAdapter.getSelectedList());
                } else {
                    showToast("当前选择的券不能使用,未发现优惠项", false);
                }
            });
        } else if (ticket.ticketType == 4) {
            // 单品优惠券,默认一张
            OrderList.getInstance().computeSingleDiscount2(ticket, discount -> {
                if (discount > 0) {
                    mTicketSelectedAdapter.add(new Payment("云会员-" + ticket.title, PayType.COUPON_TYPE,
                            BigDecimal.valueOf(ticket.money).multiply(BigDecimal.valueOf(1)).setScale(2, BigDecimal.ROUND_HALF_UP).floatValue(),
                            Math.min(mMoney.getUnpaidFloat(), discount), 1, ticket.id));

                    OrderList.getInstance().computeCloudMoneyWithPayment(mTicketSelectedAdapter.getSelectedList());
                } else {
                    showToast("当前选择的券不能使用,未发现优惠项", false);
                }
            });
        }
    }

    private void handleTable() {
        mTicketSelectedAdapter = new TicketSelectedAdapter(mBinding.selectedRecyclerView, () -> {
            OrderList.getInstance().computeCloudMoneyWithPayment(mTicketSelectedAdapter.getSelectedList());
        });
        mBinding.selectedRecyclerView.setAdapter(mTicketSelectedAdapter);
    }

    /**
     * @return 获取劵张数
     */
    private int getCouponTypeNum() {
        int num = 0;

        List<Payment> list = mTicketSelectedAdapter.getSelectedList();
        for (int i = 0; i < list.size(); i++) {
            Payment p = mTicketSelectedAdapter.getItem(i);

            if (p != null && p.payType == PayType.COUPON_TYPE) {
                num += p.ticketNum;
            }
        }

        return num;
    }


    /**
     * 当前点击的ticket是否已经选择过
     *
     * @param ticket 点击的ticket
     * @return true, 已经选择; false,未选择
     */
    private boolean isTicketSelected(Ticket ticket) {
        boolean result = false;

        List<Payment> paymentList = mTicketSelectedAdapter.getSelectedList();
        for (Payment p : paymentList) {
            String title = p.title.replace("云会员-", "");
            if (title.equals("积分抵扣金额")) {
                result = true;
                break;
            } else if (title.equals(ticket.title)) {
                result = true;
                break;
            }
        }

        return result;
    }

    // --

    public void setOnButtonClickListener(OnButtonClickListener onButtonClickListener) {
        mOnButtonClickListener = onButtonClickListener;
    }

    private OnButtonClickListener mOnButtonClickListener;

    public interface OnButtonClickListener {
        void onWeixinPayClick(float payMoney);

        void onAlipayClick(float payMoney);

        void onLogoutClick();

        void onConfirmPayClick();

        void onBackCartClick();
    }
}
